package com.ruoyi.walmart.service.auth.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.commodity.mapper.AuthBrandMapper;
import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.WalmartConstant;
import com.ruoyi.common.core.domain.AuthBrand;
import com.ruoyi.common.core.domain.Platform;
import com.ruoyi.common.core.domain.ProductCates;
import com.ruoyi.common.core.domain.TreeSelect;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.walmart.domain.auth.ShopAuth;
import com.ruoyi.walmart.mapper.auth.PlatformMapper;
import com.ruoyi.walmart.mapper.auth.ShopAuthMapper;
import com.ruoyi.walmart.service.auth.ShopAuthService;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service
@Log4j2
public class ShopAuthServiceImpl implements ShopAuthService {

	@Autowired
	ShopAuthMapper shopAuthMapper;
	@Autowired
	PlatformMapper platformMapper;

	@Autowired
	AuthBrandMapper authBrandMapper;

	/**
	 * 对密钥进行编码
	 *
	 * @param clientId     key
	 * @param clientSecret 秘钥
	 * @return bese64编码字符串
	 */
	public static String getAuthorization(String clientId, String clientSecret) {
		String str = clientId + ":" + clientSecret;
		return "Basic " + Base64.encodeBase64String(str.getBytes());
	}

	/**
	 * 获取美国店铺的token
	 *
	 * @return
	 */
	public static String getAccessToken(String authorization) {
		String accessToken = "";
		Map<String, String> headers = new HashMap<>();
		headers.put("Authorization", authorization);
		headers.put("WM_SVC.NAME", WalmartConstant.ACCOUNT_NAME);
		headers.put("WM_QOS.CORRELATION_ID", IdUtil.randomUUID());
		try {
			HttpResponse response = HttpRequest.post("https://marketplace.walmartapis.com" + "/v3/token")
					.addHeaders(headers)
					.body("grant_type=client_credentials", "application/x-www-form-urlencoded")
					.execute();

			JSONObject jsonObject = JSONUtil.parseObj(response.body());
			accessToken = jsonObject.getStr("access_token");
			if (accessToken == null) {
				log.error("walmart获取token请求失败body:{}", response.body());
				throw new ServiceException("获取沃尔玛接口调用凭证失败", 500);
			}
		} catch (Exception e) {
			log.error("【获取美国站点token值异常】，{}", e.getMessage());
			throw new ServiceException("获取美国站点token值异常", 500);
		}
		return accessToken;
	}

	@Override
	public int authFlay(ShopAuth shopAuth) {
		String authorization = getAuthorization(shopAuth.getClientId(), shopAuth.getClientSecret());
		int count = shopAuthMapper.countByAuth(shopAuth);
		if (shopAuth.getSite().equals("US")) {
			if (count <= 0) {
				String accessToken = getAccessToken(authorization);
				if (accessToken != null) {
					if (shopAuth.getAuthBrandIds().isEmpty()) {
						throw new ServiceException("未选择品牌请检查！");
					}
					// 将品牌id转换成可存储的字符串
					String authBrandId = shopAuth.getAuthBrandIds().stream()
							.map(String::valueOf)  // 将 Long 转换为 String
							.collect(Collectors.joining(","));// 用逗号连接每个字符串
					shopAuth.setAuthBrandId(authBrandId);
					shopAuth.setAuthDate(DateUtils.getNowDate());
					shopAuth.setCreateTime(DateUtils.getNowDate());
					int i = shopAuthMapper.shopAuthInsert(shopAuth);
					Platform platform = Optional.of(new Platform())
							.map(p -> {
								p.setParentId(2L);
								p.setAuthId(Long.toString(shopAuth.getAuthId()));
								p.setShopName(shopAuth.getShopName());
								p.setCreateTime(DateUtils.getNowDate());
								return p;
							})
							.orElseThrow(() -> new IllegalStateException("Failed to create Platform object"));
					platformMapper.insertAll(platform);
//					if (true) throw new ServiceException("");
					return i;
				}
			}
			throw new ServiceException("存在相同的密钥！", 500);
		}
		throw new ServiceException("获取站点错误！", 500);
	}

	@Override
	public List<ShopAuth> selectAllList(ShopAuth shopAuth) {
		// 查询品牌名称，并将其存入Map中以便快速查找
		List<AuthBrand> authBrands = authBrandMapper.selectList(null);
		Map<Long, AuthBrand> authBrandMap = authBrands.stream()
				.collect(Collectors.toMap(AuthBrand::getAuthBrandId, brand -> brand));

		// 查询 ShopAuth 列表
		List<ShopAuth> shopAuths = shopAuthMapper.selectAllList(shopAuth);

		// 遍历 ShopAuth 列表并为每个对象设置品牌名称
		shopAuths.forEach(item -> {
			List<Long> authBrandIds = convertToLongList(item.getAuthBrandId()); // 转换为 Long 列表
			String brandNames = authBrandIds.stream()
					.map(authBrandMap::get) // 获取 AuthBrand 对象
					.filter(Objects::nonNull) // 排除 null 值
					.map(AuthBrand::getBrandName) // 提取品牌名称
					.collect(Collectors.joining("、")); // 将品牌名称通过逗号连接成一个字符串

			item.setBrandName(brandNames); // 设置品牌名称
		});

		return shopAuths;
	}

	public static List<Long> convertToLongList(String authBrandId) {
		// 转换字符串为 Long 列表
		if (authBrandId == null || authBrandId.trim().isEmpty()) {
			return Collections.emptyList(); // 为空字符串时直接返回空列表
		}

		return Arrays.stream(authBrandId.split(","))
				.map(String::trim)  // 去掉多余的空格
				.map(Long::parseLong) // 转换为 Long
				.collect(Collectors.toList()); // 收集到 List 中
	}

	@Override
	public int deleteByAuthIdInt(Long authId) {
		int i = shopAuthMapper.deleteByAuthIdInt(authId);
		platformMapper.deleteByAuthIdInt(authId);
		return i;
	}

	@Override
	public int updateShopAuth(ShopAuth shopAuth) {
		String authorization = getAuthorization(shopAuth.getClientId(), shopAuth.getClientSecret());
		int count = shopAuthMapper.countByAuth(shopAuth);
		if (shopAuth.getSite().equals("US")) {
			if (count <= 0) {
				String accessToken = getAccessToken(authorization);
				if (accessToken != null) {
					if (shopAuth.getAuthBrandIds().isEmpty()) {
						throw new ServiceException("未选择品牌请检查！");
					}
					// 将品牌id转换成可存储的字符串
					String authBrandId = shopAuth.getAuthBrandIds().stream()
							.map(String::valueOf)  // 将 Long 转换为 String
							.collect(Collectors.joining(","));// 用逗号连接每个字符串
					shopAuth.setAuthBrandId(authBrandId);
					shopAuth.setAuthDate(DateUtils.getNowDate());
					shopAuth.setUpdateTime(DateUtils.getNowDate());
					int i = shopAuthMapper.updateShopAuth(shopAuth);
					Platform platform = Optional.of(new Platform())
							.map(p -> {
								p.setShopName(shopAuth.getShopName());
								p.setUpdateTime(DateUtils.getNowDate());
								p.setAuthId(Long.toString(shopAuth.getAuthId()));
								return p;
							})
							.orElseThrow(IllegalArgumentException::new);
					platformMapper.updatePlatform(platform);
					return i;
				}
			}
			throw new ServiceException("存在相同的密钥！", 500);
		}
		throw new ServiceException("获取站点错误！", 500);
	}

	@Override
	public ShopAuth selectByAuthId(Long authId) {
		return shopAuthMapper.selectByAuthId(authId);
	}

	@Override
	@DataScope(AuthBrandAlias = "a")
	public List<AuthBrand> selectAuthBrand(AuthBrand authBrand) {
		return shopAuthMapper.selectAuthBrand(authBrand);
	}

	@Transactional
	@Override
	public int authBrandInsert(AuthBrand authBrand) {
		// 查询新增品牌是否已经存在
		int result = shopAuthMapper.selectCount(authBrand.getBrandName());
		if (result > 0) {
			throw new ServiceException("该品牌名称已存在！");
		}
		String brandNumber = authBrand.getBrandName() + "-001";
		authBrand.setBrandNumber(brandNumber);
		authBrand.setCreateTime(DateUtils.getNowDate());
		shopAuthMapper.authBrandInsert(authBrand);

		// 新增子品牌
		AuthBrand brand = new AuthBrand();
		BeanUtils.copyProperties(authBrand, brand);// 赋值属性
		brand.setAuthBrandId(null); // 赋值为空，使其自动重新赋值
		brand.setBrandNumber(Constants.NEUTRAL + brandNumber);// 品牌编号
		brand.setBrandName(Constants.NEUTRAL + authBrand.getBrandName());// 品牌名称
		brand.setParentId(authBrand.getAuthBrandId());

		return shopAuthMapper.authBrandInsert(brand);
	}

	@Override
	public AuthBrand selectByAuthBrandId(Long authBrandId) {
		return shopAuthMapper.selectByAuthBrandId(authBrandId);
	}

	@Transactional
	@Override
	public int updateAuthBrand(AuthBrand authBrand) {
		int result = shopAuthMapper.selectCountByAuthBrand(authBrand.getAuthBrandId());
		if (result <= 0) {
			throw new ServiceException("修改的品牌不存在,请刷新页面重试！");
		}
		authBrand.setUpdateTime(DateUtils.getNowDate());
		// 修改对应的子品牌
		shopAuthMapper.updateAuthBrandByParentId(authBrand.getAuthBrandId(), Constants.NEUTRAL + authBrand.getBrandName());
		return shopAuthMapper.updateAuthBrand(authBrand);
	}

	@Transactional
	@Override
	public int updateByAuthBrandId(Long authBrandId) {
		// 删除对应的子品牌
		shopAuthMapper.deleteByAuthParentId(authBrandId);
		return shopAuthMapper.updateByAuthBrandId(authBrandId);
	}

	@Override
	public List<TreeSelect> selectAuthBrandTreeList(AuthBrand authBrand) {
		List<AuthBrand> authBrandList = SpringUtils.getAopProxy(this).selectAuthBrand(authBrand);
		return buildAuthBrandTreeSelect(authBrandList);
	}

	@Override
	public List<AuthBrand> buildAuthBrandTree(List<AuthBrand> authBrandList) {
		List<AuthBrand> returnList = new ArrayList<>();
		List<Long> collect = authBrandList.stream().map(AuthBrand::getAuthBrandId).collect(Collectors.toList());
		for (AuthBrand authBrand : authBrandList) {
			//如果是顶节点，遍历该父节点下的所以子节的
			if (!collect.contains(authBrand.getParentId())) {
				recursionFn(authBrandList, authBrand);
				returnList.add(authBrand);
			}
		}
		if (returnList.isEmpty()) {
			returnList = authBrandList;
		}
		return returnList;
	}

	/**
	 * 递归列表
	 *
	 * @param authBrandList 子级
	 * @param authBrand     父级
	 */
	private void recursionFn(List<AuthBrand> authBrandList, AuthBrand authBrand) {
		// 得到子节点列表
		List<AuthBrand> childList = getChildList(authBrandList, authBrand);
		authBrand.setChildrenAuthBrandForm(childList);
		for (AuthBrand newAuthBrand : childList) {
			if (hasChild(authBrandList, newAuthBrand)) {
				recursionFn(authBrandList, newAuthBrand);
			}
		}
	}

	/**
	 * 获得子节点
	 *
	 * @param authBrandList
	 * @param authBrand
	 * @return
	 */
	private List<AuthBrand> getChildList(List<AuthBrand> authBrandList, AuthBrand authBrand) {
		List<AuthBrand> returnList = new ArrayList<>();
		Iterator<AuthBrand> iterator = authBrandList.iterator();
		while (iterator.hasNext()) {
			AuthBrand n = (AuthBrand) iterator.next();
			if (StringUtils.isNotNull(n.getParentId()) && n.getParentId().longValue() == authBrand.getAuthBrandId().longValue()) {
				returnList.add(n);
			}
		}
		return returnList;
	}

	/**
	 * 判断是否有子节点
	 */
	private boolean hasChild(List<AuthBrand> authBrandList, AuthBrand authBrand) {
		return getChildList(authBrandList, authBrand).size() > 0;
	}

	@Override
	public List<TreeSelect> buildAuthBrandTreeSelect(List<AuthBrand> authBrandList) {
		List<AuthBrand> authBrandTree = buildAuthBrandTree(authBrandList);
		return authBrandTree.stream().map(TreeSelect::new).collect(Collectors.toList());
	}

	/**
	 * 根据店铺名称查询店铺信息
	 *
	 * @param shopName
	 * @return
	 */
	@Override
	public ShopAuth selectShopAuthByShopName(String shopName) {
		return shopAuthMapper.selectShopAuthByShopName(shopName);
	}


}
